<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Book;
use Illuminate\Support\Facades\File;
use GuzzleHttp\Client;
use Asymptix\HtmlDomParser\HtmlDomParser;
use App\Models\Operation;
use App\Models\Section;
use App\Jobs\getBookSectionsFromQuanShuWu;

class DownloadBooksFromQuanShuWu extends Command {
	
	protected $signature = 'quanben-download {from} {to}';
	protected $description = 'download books from quan ben shu wu';
	
	public function __construct() {
		parent::__construct ();
	}
	
	public function handle() {
		$from = $this->argument('from');
		$to = $this->argument('to');
		$this->warn('采集全本书屋各分类书籍!');
		$hrefs = [];
		for($i = $from; $i <= $to; $i++) {
			for($j = 2; $j <= 9; $j++) {
				$url = 'http://www.quanshuwu.com/category/'.$j.'_1_'.$i.'.aspx';
				$html = new HtmlDomParser();
				$html->loadUrl($url);
				foreach ($html->find('.storelistbt5') as $book) {
					$hrefs[] = 'http://www.quanshuwu.com'.$book->find('a', 0)->href;
				}
				unset($html);
			}
		}
		$x = 1;
		$ch = count($hrefs);
		foreach($hrefs as $href) {
			$html = new HtmlDomParser();
			$html->loadUrl($href);
			if(!is_null($html->find('h1'))) {
				if(count($html->find('#readlist', 0)->find('li')) > 800) {
					$this->info($x .'/'.$ch.'  '.$html->find('h1', 0)->plaintext.' 查找成功，加入队列执行');
					dispatch(new getBookSectionsFromQuanShuWu($href));
				}else {
					$this->error($x .'/'.$ch.'  '.$html->find('h1', 0)->plaintext.' 不足800章，放弃采集');
				}
			}else {
				$this->error($x .'/'.$ch.' 此页无书籍');
			}
			$x++;
			unset($url);
			unset($html);
		}
		$this->error('循环结束!');
	}
}
